#pragma once
#include <sys/epoll.h>
#include <string.h>
#include "Log.hpp"
#include "Err.hpp"

const static int defaultfd = -1;
class Epoll
{
    const static int gsize = 128;

public:
    Epoll() : epfd(defaultfd)
    {
    }
    void Create()
    {
        int fd = epoll_create(gsize);
        if (fd < 0) // 创建失败
        {
            logMessage(Error, "epoll_create error,code:%d,string:%s", errno, strerror(errno));
            exit(EPOLL_CREATE_ERROR);
        }
        epfd = fd;
    }
    bool AddEvent(int fd, uint32_t Ev)
    {
        struct epoll_event event;
        event.events = Ev; // 读事件
        event.data.fd = fd;
        return epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event) == 0; // 成功：返回0。 失败：返回-1。
    }
    bool DelEvent(int fd)
    {
        return epoll_ctl(epfd,EPOLL_CTL_DEL,fd,nullptr) == 0; //删除的时候，对事件不进行处理
    }
    int Wait(struct epoll_event *events, int maxevents, int timeout) // 成功：返回准备好的文件描述符的数量;失败：返回-1
    {
        return epoll_wait(epfd, events, maxevents, timeout);
    }
    int Fd()
    {
        return epfd;
    }
    void Close()
    {
        close(epfd);
    }
    ~Epoll()
    {
        if (epfd != defaultfd)
            Close();
    }

private:
    int epfd;
};